<template>
  <layout-content
    v-loading="uiState.loading"
    :header="$t('commons.button.create')"
    :back-to="{ name: 'Namespaces' }"
  >
    <br />
    <div>
      <div class="grid-content bg-purple-light">
        <div style="float: right; margin-top: 10px">
          <el-button @click="back()">
            {{ $t("commons.button.cancel") }}
          </el-button>
          <el-button v-if="!uiState.yaml" @click="onEditYaml()">
            {{ $t("commons.button.yaml") }}
          </el-button>
          <el-button v-if="uiState.yaml" @click="backToForm()">
            {{ $t("commons.button.back_form") }}
          </el-button>
          <el-button
            v-loading="uiState.loading"
            type="primary"
            @click="onSubmit"
          >
            {{ $t("commons.button.submit") }}
          </el-button>
        </div>
      </div>
      <div v-if="!uiState.yaml" class="grid-content bg-purple-light">
        <el-form
          ref="form"
          label-position="top"
          :model="namespace"
          :rules="namespaceRules"
        >
          <el-col :span="12">
            <el-form-item
              :label="$t('commons.table.name')"
              prop="metadata.name"
            >
              <el-input v-model="namespace.metadata.name" clearable />
            </el-form-item>
          </el-col>
        </el-form>
        <el-col :span="24">
          <br />
          <el-tabs
            v-model="uiState.activeTab"
            tab-position="top"
            type="border-card"
          >
            <el-tab-pane
              :label="$t('business.workload.labels_annotations')"
              name="label"
            >
              <ko-key-value
                v-model:value="namespace.metadata.labels"
                :title="$t('business.workload.label')"
              />
              <ko-key-value
                v-model:value="namespace.metadata.annotations"
                :title="$t('business.workload.annotations')"
              />
            </el-tab-pane>

            <el-tab-pane label="Resource Quotas" name="quotas">
              <ko-resource-quota
                ref="ko_resource_quota"
                style="margin-left: 20px"
                :hasSelector="false"
                :resourceQuotaObj="quotaForm.spec"
              />
            </el-tab-pane>

            <el-tab-pane label="Limit Range" name="limit">
              <ko-limit-range
                ref="ko_limit_range"
                style="margin-left: 20px"
                :limitRangeObj="
                  rangeForm.spec.limits.length === 0
                    ? null
                    : rangeForm.spec.limits[0]
                "
              />
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </div>
      <div v-else class="grid-content bg-purple-light">
        <yaml-editor ref="yaml_editor" :value="submitReq" />
      </div>
    </div>
  </layout-content>
</template>

<script setup lang="ts">
import LayoutContent from "@/views/domain/kubeHud/views/components/layout/LayoutContent.vue";
import YamlEditor from "@/views/domain/kubeHud/views/components/yaml-editor/index.vue";
import KoKeyValue from "@/views/domain/kubeHud/views/components/ko-configuration/ko-key-value.vue";
import KoLimitRange from "@/views/domain/kubeHud/views/components/ko-configuration/ko-limit-range.vue";
import KoResourceQuota from "@/views/domain/kubeHud/views/components/ko-configuration/ko-resource-quota.vue";
import { computed, reactive, ref } from "vue";

import {
  LimitRange,
  ListResponse,
  Namespace,
  ResourceQuota,
  useK8SApi
} from "@/views/domain/kubeHud/api/k8s";
import { useFormRule } from "@/views/domain/kubeHud/utils/rules";
import { useVerifyRouter } from "@/router/use";
import { ElMessage, ElMessageBox } from "element-plus";
import { useI18n } from "vue-i18n";
import { SafePromiseAll } from "@/utils/promise";

// import { createNamespace } from "@/api/namespaces";
// import Rule from "@/utils/rules";
// import Bus from "@/utils/bus";
// import { createResourceQuota } from "@/api/resourcequota";
// import { createLimitRange } from "@/api/limitranges";
const { namespaceRepo, limitRangeRepo, quotasRepo } = useK8SApi();

const { t } = useI18n();
const { RequiredRule } = useFormRule();
const router = useVerifyRouter();
const uiState = reactive({
  loading: false,
  yaml: false,
  activeTab: "label"
});

const _submitRes = ref<ListResponse>({
  apiVersion: "v1",
  kind: "List",
  items: []
});

const submitReq = computed(() => getSubmitRequest());
const getSubmitRequest = () => {
  _submitRes.value.items = [namespace.value];
  if (quotaForm.value.metadata?.name) {
    _submitRes.value.items.push(quotaForm.value);
  }
  if (rangeForm.value.metadata?.name) {
    _submitRes.value.items.push(rangeForm.value);
  }
  return _submitRes.value.items.length > 1
    ? _submitRes.value.items
    : _submitRes.value.items[0];
};

const namespace = ref<Namespace>({
  apiVersion: "v1",
  kind: "Namespace",
  metadata: {
    name: "",
    labels: {},
    annotations: {}
  }
});

const quotaForm = ref<ResourceQuota>({
  apiVersion: "v1",
  kind: "ResourceQuota",
  metadata: {
    name: "",
    namespace: ""
  },
  spec: {}
});

const rangeForm = ref<LimitRange>({
  apiVersion: "v1",
  kind: "LimitRange",
  metadata: {
    name: "",
    namespace: ""
  },
  spec: { limits: [] }
});

const namespaceRules = ref({
  "metadata.name": [RequiredRule]
});

const back = () => {
  router.back();
};

const onEditYaml = () => {
  uiState.yaml = true;
};

const backToForm = () => {
  ElMessageBox.confirm(
    t("commons.confirm_message.back_form"),
    t("commons.message_box.prompt"),
    {
      confirmButtonText: t("commons.button.confirm"),
      cancelButtonText: t("commons.button.cancel"),
      type: "warning"
    }
  ).then(() => {
    uiState.yaml = false;
  });
};

const onSubmit = () => {
  const requests = [namespaceRepo.createNamespace({}, namespace.value)];
  if (quotaForm.value.metadata?.name) {
    requests.push(quotasRepo.create(quotaForm.value));
  }
  if (rangeForm.value.metadata?.name) {
    requests.push(limitRangeRepo.create(rangeForm.value));
  }
  uiState.loading = false;
  SafePromiseAll(requests)
    .then(res => {
      if (res.every(e => e.ok)) {
        back();
      } else {
        ElMessage.error(t("commons.msg.create_failed"));
      }
    })
    .finally(() => {
      uiState.loading = false;
    });
};
</script>

<style scoped></style>
